<?php

namespace app\admin\controller\user;

use app\common\controller\AdminController;
use app\services\user\UserService;
use think\App;

/**
 * Class User
 * @package app\admin\controller\user
 */
class User extends AdminController
{
    /**
     * @var UserService
     */
    private $service;

    public function __construct(App $app, UserService $service)
    {
        parent::__construct($app);

        $this->service = $service;
        $this->assign('getSexList', $this->service->getSexList());
        $this->assign('getIsDisableList', $this->service->getIsDisableList());
    }

    /**
     * Description: 获取首页列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @return mixed|\think\response\Json
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            return layuiTabSuc($this->service->getSysList($this->request->get()));
        }
        return $this->fetch();
    }

    /**
     * Description: 添加数据
     *
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $this->service->save($this->request->post());
            $this->success('保存成功');
        }
        return $this->fetch();
    }

    /**
     * Description: 编辑数据
     *
     * @param int $id
     *
     * @return mixed
     */
    public function edit(int $id)
    {
        $row = $this->service->get($id);
        if ($row->isEmpty()) {
            $this->error('数据不存在');
        }

        if ($this->request->isPost()) {
            $row->save($this->request->post());
            $this->success('保存成功');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * Description: 删除数据
     *
     * @param array|int $id 删除id
     */
    public function delete($id)
    {
        $this->service->delete($id);
        $this->success('删除成功');
    }

    /**
     * Description: 导出数据
     *
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function export()
    {
        $this->service->exportData($this->request->get());
    }

    /**
     * Description: 更新指定字段
     *
     * @param int    $id
     * @param string $field
     * @param string $value
     */
    public function setField(int $id, string $field, string $value)
    {
        $this->service->update($id, [$field => $value]);
        $this->success('修改成功！');
    }

    /**
     * Description:指定用户发优惠券
     *
     * @return mixed
     */
    public function releaseCoupon()
    {
        $this->assign('ids', $this->request->get('ids'));
        return $this->fetch();
    }

}